<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box1 {
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
            left: 0px;
            top: 0px;
        }

        .box2 {
            width: 100px;
            height: 100px;
            background-color: blue;
            position: absolute;
            left: 500px;
            top: 0px;
        }
    </style>
</head>

<body>
    <div class="box1"></div>
    <div class="box2"></div>
    <script>
        // 红色方块可以拖动 
        var box1Ele = document.querySelector(".box1");  // 红色方块 就是A
        var box2Ele = document.querySelector(".box2"); // 蓝色方块 就是B；
        box1Ele.onmousedown = function (e) {
            var x = e.clientX - this.offsetLeft;
            var y = e.clientY - this.offsetTop;
            this.onmousemove = function (e) {
                var xx = e.clientX;
                var yy = e.clientY;
                this.style.left = xx - x + "px"
                this.style.top = yy - y + "px";

                if( isCrash(box1Ele,box2Ele)){
                    console.log("碰了");
                }else {
                    console.log("未碰撞");
                }


            }
            document.onmouseup = function () {
                console.log("鼠标抬起了");
                box1Ele.onmousemove = "";
            }
        }

        // 1. 补全y轴  2.实现红色方块移动 碰到蓝色之后再回来 。


        // 提取成一个检测碰撞的函数 ，提高复用性

        // 检测碰撞的函数
        function isCrash(box1Ele, box2Ele) {
            // 检测 box1 和box2 在x轴上是否碰撞了；
            var minAx = box1Ele.offsetLeft;
            var maxAx = box1Ele.offsetLeft + box1Ele.offsetWidth;

            var minAy = box1Ele.offsetTop;
            var maxAy = box1Ele.offsetTop + box1Ele.offsetHeight;


            var minBx = box2Ele.offsetLeft;
            var maxBx = box2Ele.offsetLeft + box2Ele.offsetWidth;

            var minBy = box2Ele.offsetTop;
            var maxBy = box2Ele.offsetTop + box2Ele.offsetHeight;

            if (maxAx >= minBx && minAx <= maxBx && maxAy >= minBy && minAy <= maxBy) {
                // console.log("碰撞了");
                return true;
            }else{
                return false;
            }
        }

    </script>
</body>

</html>